import React, { Component } from 'react';
import {
    Dimensions,AsyncStorage,TouchableOpacity,Image
} from 'react-native';
import * as DATA from '../data/data';

// 58 app 只有竖屏模式，所以可以只获取一次 width
const deviceWidthDp = Dimensions.get('window').width;
// UI 默认给图是 640
const uiWidthPx = 640;

export default function pxToDp(uiElementPx) {
return uiElementPx *  deviceWidthDp / uiWidthPx;
}

//制保留2位小数，如：2，会在2后面补上00.即2.00
export function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x*100)/100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

export function fetchData(type, url, data, callback, datatype){
    let body = '';
    fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body:"phone=${}&pwd=${}&keyN=value"
    })
        .then((response) => {       // 数据解析方式
            response.json();
        })
        .then((responseData) => {       // 获取到的数据处理

        })
        .catch((error) => { // 错误处理
            alert('获取数据失败，请重试！');
        })
        .done();
}

export function saveFavoriteItem(key,value) {
    AsyncStorage.setItem(key,value,(error,result)=>{
        if (!error) {//更新Favorite的key
            //alert('success');
        }
    });
}

/**
 * 更新Favorite key集合
 * @param isAdd true 添加,false 删除
 * **/
export function updateFavoriteKeys(key,isAdd){
    AsyncStorage.getItem(this.favoriteKey,(error,result)=>{
        if (!error) {
            var favoriteKeys=[];
            if (result) {
                favoriteKeys=JSON.parse(result);
            }
            var index=favoriteKeys.indexOf(key);
            if(isAdd){
                if (index===-1)favoriteKeys.push(key);
            }else {
                if (index!==-1)favoriteKeys.splice(index, 1);
            }
            AsyncStorage.setItem(this.favoriteKey,JSON.stringify(favoriteKeys));
        }
    });
}

export function setValue(key,value){
    AsyncStorage.setItem(key,value);
}

export function getValue(key){
    AsyncStorage.getItem(key,(error, result)=>{
        if(!error){
            return result;
        }
    });
}

export function removeKey(key){
    AsyncStorage.removeItem(
        key,
        (error)=>{
            if(!error){
                console.log('移除成功');
            }
        }
    )
}

export function shareBtn(){
    return DATA.ISHARED?<TouchableOpacity
        onPress={() => {
                //TODO
                }}>
        <Image
            source={{uri:DATA.app_pic + 'share.png'}}
            style={{
                        marginRight: pxToDp(20),
                        width: pxToDp(45),
                        height:pxToDp(64)
                }}>
        </Image>
    </TouchableOpacity>:null;
}

export function _show(context,txt,time){
    context.setState({
        isModal: true,
        alertTxt: txt
    });
    if(time > 0){
        context.timer = setTimeout(() => {context._hide()},time);
    }
}

export function _hide(context){
    context.setState({
        isModal:false
    })
}

//export function fetchData(){
//
//}
